"""
In order to avoid all the weird problem arise from type mismatch, I move some code here
"""
from pylab import *
from scipy import *
from scipy import optimize
import DB
from Configuration import Configuration

def showTime(expId, expName, low, upper, isShow = True):
    maxId = Configuration.getId()
    timeArray = {0:0}
    countArray = {0:0}
    for i in xrange(1, upper + 1):
        countArray[i] = 0
        timeArray[i] = 0
    for id in xrange(1, maxId+1/1):
        if(expId != 0 and id !=expId):
            continue
        lines = DB.getAllTime(id, expName)
        for line in lines:
            if(line[2] <= 0): continue
            print line
            timeArray[line[1]] = timeArray[line[1]] + line[2]
            countArray[line[1]] = countArray[line[1]] + 1
    x = []
    y = []
    for i in xrange(low, upper + 1):
#        print i, timeArray[i]/countArray[i]
        x.append(i)
        y.append(timeArray[i]/countArray[i])
#    if(isShow):
#        barplot(x, y)

    return (x,y)

def predictTimeFunctionFit(fun, expId, expName, low, upper, p0):
    x,y = showTime(expId, expName, low, upper, False)
    errfunc = lambda p, x1, y1: fun(p, x1) -y1
    p1, success = optimize.leastsq(errfunc, p0[:], args=(array(x),array(y)))
    x2 = xrange(x[0], x[0] + len(x) + 2)
    print p1, " ", success
    plot(x,y, 'ro')
    plot(x2, fun(p1,x2),'g')
    legend(['original','regression'])
    show()
    return True    

if __name__ == "__main__":
#    num_points = 150
#    Tx = linspace(5., 8., num_points)
#    fun = lambda p, x: p[0]*x * sin(p[1] * x + p[2]) + p[3] * x
#    predictTimeFunctionFit(fun, 32, "1a1", 1, 16, [0,1,1,1])
    fun = lambda p, x: p[0] * x * x * x * x * x *x + p[1] *x*x * x * x * x + p[2] *x*x *x *x + p[3] *x*x*x + p[4] *x*x + p[5] *x + p[6]
    predictTimeFunctionFit(fun, 32, "1a1", 1, 16, [0,1,1,1,1,1,1])
# if you experience problem "optimize not found", try to uncomment the following line. The problem is present at least at Ubuntu Lucid python scipy package
# from scipy import optimize

# Generate data points with noise
#    num_points = 150
#    Tx = linspace(5., 8., num_points)
#    Ty = Tx
#    
#    tX = 11.86*cos(2*pi/0.81*Tx-1.32) + 0.64*Tx+4*((0.5-rand(num_points))*exp(2*rand(num_points)**2))
#    tY = -32.14*cos(2*pi/0.8*Ty-1.94) + 0.15*Ty+7*((0.5-rand(num_points))*exp(2*rand(num_points)**2))
#    fitfunc = lambda p, x: p[0]*cos(2*pi/p[1]*x+p[2]) + p[3]*x # Target function
#    errfunc = lambda p, x, y: fitfunc(p, x) - y # Distance to the target function
#    p0 = [-15., 0.8, 0., -1.] # Initial guess for the parameters
#    p1, success = optimize.leastsq(errfunc, p0[:], args=(Tx, tX))
#    
#    time = linspace(Tx.min(), Tx.max(), 100)
#    plot(Tx, tX, "ro", time, fitfunc(p1, time), "r-") # Plot of the data and the fit
#    
#    # Fit the second set
#    p0 = [-15., 0.8, 0., -1.]
#    p2,success = optimize.leastsq(errfunc, p0[:], args=(Ty, tY))
#    
#    time = linspace(Ty.min(), Ty.max(), 100)
#    plot(Ty, tY, "b^", time, fitfunc(p2, time), "b-")
#    
#    # Legend the plot
#    title("Oscillations in the compressed trap")
#    xlabel("time [ms]")
#    ylabel("displacement [um]")
#    legend(('x position', 'x fit', 'y position', 'y fit'))
#    
#    ax = axes()
#    
#    text(0.8, 0.07,
#         'x freq :  %.3f kHz \n y freq :  %.3f kHz' % (1/p1[1],1/p2[1]),
#         fontsize=16,
#         horizontalalignment='center',
#         verticalalignment='center',
#         transform=ax.transAxes)
#    
#    show()
